package cn.bubi.sdk.starter;

import cn.bubi.access.starter.BlockchainProperties;
import cn.bubi.access.utils.blockchain.BlockchainKeyPair;
import cn.bubi.access.utils.blockchain.SecureKeyGenerator;
import cn.bubi.sdk.core.operation.impl.CreateAccountOperation;
import cn.bubi.sdk.core.spi.BcOperationService;
import cn.bubi.sdk.core.transaction.model.TransactionCommittedResult;
import cn.bubi.sdk.core.utils.GsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;

@SpringBootApplication
@RestController
public class App {
    private Logger logger = LoggerFactory.getLogger(App.class);
    @Autowired
    private BcOperationService bcOperationService;

    @Autowired
    private BlockchainProperties blockchainProperties;

    @RequestMapping("/xxx")
    public String hello() {
        return "HELLO WORLD";
    }
    @RequestMapping("/createAccount")
    public String createAccount() throws Exception{
        BlockchainProperties.SponsorAccountPoolConfig accountPool = blockchainProperties.getAccountPool();
        BlockchainKeyPair keyPair = SecureKeyGenerator.generateBubiKeyPair();
        TransactionCommittedResult commit = bcOperationService
                .newTransaction(accountPool.getAddress())
                .buildAddOperation(new CreateAccountOperation.Builder().buildDestAddress(keyPair.getBubiAddress()).build())
                .buildAddSigner(accountPool.getPublicKey(), accountPool.getPrivateKey()).commit(false);
        logger.info("commit result: {}", GsonUtil.toJson(commit));
        return GsonUtil.toJson(commit);
    }

    public static void main(String[] args) {
        SpringApplication.run(App.class, args);
    }
    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

//            String[] beanNames = ctx.getBeanDefinitionNames();
//            Arrays.sort(beanNames);
//            for (String beanName : beanNames) {
//                System.out.println(beanName);
//            }

        };
    }
}
